package com.jacob.androidframe.controls;

import com.jacob.androidframe.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ImageViewAutoStretchRatio extends ImageView
{
	public static final int		FIX_WIDTH				= 0;
	public static final int		FIX_HEIGHT				= 1;
	
	private static final int	DEFAULT_FIX	= FIX_WIDTH;
	private static final float	DEFAULT_RATIO= 1.0f;

	private int					mFix;
	private float					mRatio;

	public ImageViewAutoStretchRatio(Context pContext)
	{
		super(pContext);
	}

	public ImageViewAutoStretchRatio(Context pContext, AttributeSet attrs)
	{
		this(pContext, attrs, 0);
	}

	public ImageViewAutoStretchRatio(Context pContext, AttributeSet attrs, int defStyle)
	{
		super(pContext, attrs, defStyle);
	
		TypedArray _TypedArray = pContext.obtainStyledAttributes(attrs, R.styleable.ImageViewAutoStretchRatio);
		mFix = _TypedArray.getInt(R.styleable.ImageViewAutoStretchRatio_fix, DEFAULT_FIX);
		mRatio = _TypedArray.getFloat(R.styleable.ImageViewAutoStretchRatio_ratio, DEFAULT_RATIO);
		_TypedArray.recycle();
	}

	@Override
	protected void onMeasure(int pWidthMeasureSpec, int pHeightMeasureSpec)
	{
		int _NewWidth = MeasureSpec.getSize(pWidthMeasureSpec);
		int _NewHeight = MeasureSpec.getSize(pHeightMeasureSpec);

		switch (mFix) {
		case FIX_WIDTH:
			_NewHeight = (int) (_NewWidth / mRatio);
			break;
		case FIX_HEIGHT:
			_NewWidth = (int) (_NewHeight * mRatio);
			break;
		default:
			throw new IllegalStateException("Unknown fix with ID " + mFix);
		}

		setMeasuredDimension(_NewWidth, _NewHeight);
	}
}
